package cz.muni.fi.xvano1.trinity.beans;

import cz.muni.fi.xvano1.trinity.core.Core;
import cz.muni.fi.xvano1.trinity.supplementary.ActionManagerBeanContext;
import cz.muni.fi.xvano1.trinity.supplementary.DataSupplier;
import cz.muni.fi.xvano1.trinity.data.Event;
import cz.muni.fi.xvano1.trinity.supplementary.CalendarHandler;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.fortuna.ical4j.model.component.VEvent;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;

/**
 * Class implements methods of removing reservation (event) from the system. Due
 * to the framework nature, getter and setter methods for parameters of request
 * have been implemented
 *
 * @author Jan Vano
 */
public class RemoveEventActionBean implements ActionBean {

    private ActionManagerBeanContext context;
    private String uid;
    private String response;
    private String newLine = "<br/>";

    /**
     * Interface method from ActionBean.
     */
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = (ActionManagerBeanContext) context;
    }

    /**
     * Interface method from ActionBean, using a co-variant return type.
     */
    @Override
    public ActionManagerBeanContext getContext() {
        return this.context;
    }

    /**
     * Method redirect user to homepage.
     *
     * @return Resolution object to framework
     */
    @DefaultHandler
    public Resolution home() {
        return new RedirectResolution("/Home");
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    /**
     * Forwards request to confirmation page. On the confirmation page all the
     * input is interpreted in its final form.
     *
     * @return Resolution to framework with necessary data
     */
    public Resolution removeEventInputConfirm() {
        String user = getContext().getUser();
        Core core = new Core(user);
        VEvent vevent = core.loadEvent(uid);
        if (vevent == null) {
            response = "Event with UID " + uid + " does not exist.";
            getContext().getRequest().setAttribute("action", "remove");
            getContext().getRequest().setAttribute("notice", response);
            return new ForwardResolution("/Index");
        } else {
            Event event = new Event(vevent);
//            setWholeDay(event.get);
            getContext().getRequest().setAttribute("summary", event.getSummary());
            getContext().getRequest().setAttribute("start", event.getStartDateTime());
            getContext().getRequest().setAttribute("end", event.getEndDateTime());
            getContext().getRequest().setAttribute("recurrence", event.getRecurrency());
            getContext().getRequest().setAttribute("startTime", event.getStartDateTime());
            getContext().getRequest().setAttribute("endTime", event.getEndDateTime());
//            getContext().getRequest().setAttribute("wholeDay", wholeDay);
            getContext().getRequest().setAttribute("description", event.getDescription());
            getContext().getRequest().setAttribute("location", event.getLocation());
            getContext().getRequest().setAttribute("uid", uid);
            getContext().getRequest().setAttribute("action", "removeEventConfirm");
            return new ForwardResolution("/Index");
        }
    }

    /**
     * Forwards request to resolution page. On the resolution user can see
     * whether the action has been completed successfuly. Reason for the action
     * is displayed.
     *
     * @return Resolution to framework with necessary data
     * @throws IOException
     * @throws InterruptedException
     */
    public Resolution removeEvent() throws IOException, InterruptedException {
        String user = getContext().getUser();
        String file = Core.userDirectory + user + ".ics";
        String tmp = Core.userDirectory + user + "_tmp.ics";
        Process p = Runtime.getRuntime().exec("cp " + file + " " + tmp);
        p.waitFor();
        Core core = new Core(user + "_tmp");
        boolean error = false;
        if (core.removeEvent(uid) != 0) {
            response = "Request status: FAILED" + newLine;
            error = true;
        } else {
            response = "Request status: Event successfuly deleted." + newLine;
        }
        response = response + "Reason: " + core.getLastMessage() + newLine;

        synchronized(getContext().getServletContext().getAttribute("userAccessSync")){
        String update = Core.scripts + "deleteEvents.php " + "'" + uid + "'";
        Process up = Runtime.getRuntime().exec(update);
        up.waitFor();
        int updateResult = up.exitValue();
        if (updateResult == 0) {
            BufferedReader r = null;
            try {
                r = new BufferedReader(new FileReader(Core.calendar));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(CalendarViewActionBean.class.getName()).log(Level.SEVERE, null, ex);
            }
            getContext().getServletContext().setAttribute("calendar", CalendarHandler.getCalendarStructure(r));
            String renameBack = "mv " + tmp + " " + file;
            Process finish = Runtime.getRuntime().exec(renameBack);
            finish.waitFor();
        } else if (updateResult == 2) {
            response = "During the removal an error occured. Please contact administrator.";
            error = true;
            String cleanup = "rm " + tmp;
            Process clean = Runtime.getRuntime().exec(cleanup);
            clean.waitFor();
        }
        
        BufferedReader r = null;
        try {
            r = new BufferedReader(new FileReader(Core.calendar));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CalendarViewActionBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (r != null){
        getContext().getServletContext().setAttribute("calendar", CalendarHandler.getCalendarStructure(r));
        }
        }
        String noticeOrError = (error ? "error" : "notice");
        getContext().getRequest().setAttribute(noticeOrError, response);
        getContext().getRequest().setAttribute("action", "load");
        List<Event> eventList = DataSupplier.loadEvents(user);
        getContext().getRequest().setAttribute("eventList", eventList);
        return new ForwardResolution("/Index");
    }
}
